package hot100.logos61To70;

/**
 * @author logos
 * date 2025/7/16 18:31
 * @version v1.0
 * @Package hot100.logos61To70
 */
public class logos66 {

    /**
     * 66. 搜索旋转排序数组
     * https://leetcode.cn/problems/search-in-rotated-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public int search(int[] nums, int target) {
            int n = nums.length;
            int index = findMin(nums);
            if (target > nums[n - 1]) {
                return binarySearch(nums, 0, index - 1, target);
            }
            return binarySearch(nums, index, n - 1, target);
        }

        private int findMin(int[] nums) {
            int n = nums.length;
            int left = 0;
            int right = n - 2;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] >= nums[n - 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            return left;
        }

        private int binarySearch(int[] nums, int left, int right, int target) {
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] < target) {
                    left = mid + 1;
                } else if (nums[mid] > target) {
                    right = mid - 1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
    }
}
